using System;
using System.Globalization;
using System.Collections;

namespace Evolve.Util.MailTemplates
{
  /// <summary>
  /// Groups a number of localized <see cref="MailTemplate"/>
  /// instances encapsulated in <see cref="TemplateData"/>
  /// objects.
  /// </summary>
  public class TemplateGroup
  {

    #region members

    /// <summary>
    /// The ID of the template definition.
    /// </summary>
    private string templateId;

    /// <summary>
    /// Contains <see cref="TemplateData"/> objects
    /// stored by their <c>CultureInfo</c>. The default
    /// template is stored by the invariant culture.
    /// </summary>
    private Hashtable templates;

    #endregion


    #region properties

    /// <summary>
    /// Gets the template data for a given template. If
    /// no template was defined for the submitted language,
    /// this indexer returns the default template if
    /// available, otherwise <c>null</c>.
    /// </summary>
    public TemplateData this[CultureInfo locale]
    {
      get { 

        while (true)
        {
          //try to load the template data by the current locale
          TemplateData data = templates[locale] as TemplateData;
          if (data != null) return data;

          if (locale != CultureInfo.InvariantCulture)
          {
            //if the locale is not available, try the parent...
            locale = locale.Parent;
          }
          else
          {
            //if it's the invariant culture, we can't go up
            break;
          }
        }


        //if we arrived here, neither a localized template that matches
        //the submitted locale nor a default template exists.
        return null;
      }
    }


    /// <summary>
    /// The ID of the template definition.
    /// </summary>
    public string TemplateId
    {
      get { return this.templateId; }
    }

    #endregion


    /// <summary>
    /// Inits the object.
    /// </summary>
	  public TemplateGroup()
	  {
      this.templates = new Hashtable();
	  }


    /// <summary>
    /// Adds a template to the internal
    /// <see cref="templates"/> list.
    /// </summary>
    /// <param name="template">New template.</param>
    public void AddTemplate(MailTemplate template)
    {
      this.templates.Add(template.Locale, template);
    }


  }
}
